# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo


class TbSrPipeline(object):
    def process_item(self, item, spider):
        print(item)
        return item

class TbMongoPipeline(object):
    def __init__(self,mongo_uri,mongo_db,mongo_coll):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
        self.mongo_coll = mongo_coll

    @classmethod
    def from_crawler(cls,crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DB'),
            mongo_coll=crawler.settings.get('MONGO_COLL')
        )

    def open_spider(self,spider):
        self.clent = pymongo.MongoClient(self.mongo_uri)
        self.db = self.clent[self.mongo_db]
        self.coll = self.db[self.mongo_coll]

    def close_spider(self,spider):
        self.clent.close()

    def process_item(self,item,spider):
        self.coll.insert_one(dict(item))
        return item
